<template>
  <base-modal
    :title="title"
    width="676px"
    :show.sync="isShow"
    :mask-closeable="false">
    <div class="add-form task-form">
        <el-form label-position="top" :model="form" :rules="rules" ref="taskForm" >
          <el-form-item :label="$t('projectManage.setting.taskSetting.taskNum')" prop="number">
            <div class="default-no">{{ $t('projectManage.setting.taskSetting.placeholder1') }}</div>
          </el-form-item>
          <el-form-item :label="$t('projectManage.setting.taskSetting.taskName')" prop="projectTaskName">
            <el-input  maxlength="20" v-model.trim="form.projectTaskName" :placeholder="$t('projectManage.setting.taskSetting.placeholder2')" show-word-limit></el-input>
          </el-form-item>
          <el-form-item :label="$t('projectManage.setting.taskSetting.taskType')" prop="taskFormId">
            <el-cascader
              ref="cascaderType"
              class="task-cascader"
              :props="taskProps"
              v-model="form.taskFormId"
              :options="typeOptions"
              :placeholder="$t('projectManage.setting.taskSetting.placeholder3')"
              @change="handleSelectType($event)"></el-cascader>
          </el-form-item>
          
          <!-- 任务设置 -->
            <el-form-item :label="$t('projectManage.setting.taskSetting.preTask')" prop="preTaskId">
                <el-select
                  class="w-100"
                  v-model="form.preTaskId"
                  multiple
                  :multiple-limit="10"
                  @focus="queryPreTaskList(form)"
                  :placeholder="$t('projectManage.setting.taskSetting.placeholder4')"
                >
                  <el-option
                    v-for="item in preTaskList"
                    :key="item.id"
                    :label="item.taskName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
            </el-form-item>

          <!-- 计划开始时间（任务类型选择paas的时候才显示）   -->
          <el-form-item v-if="form.taskType === 'PAAS_TASK' && !isEmpty(form.taskFormId)" :label="$t('common.form.type.planStartTime')" prop="projectTaskStartTimeField">
            <el-select
              class="w-100"
              v-model="form.projectTaskStartTimeField"
              :placeholder="$t('projectManage.setting.taskSetting.timeFieldPlace')"
              clearable
              filterable
              @change="updateProjectTaskStartTime"
            >
              <el-option
                v-for="item in paasTimeFields"
                :key="`${item.fieldName}_start`"
                :label="item.displayName"
                :value="item.fieldName"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 计划结束时间（任务类型选择paas的时候才显示）   -->
          <el-form-item v-if="form.taskType === 'PAAS_TASK' && !isEmpty(form.taskFormId)" :label="$t('common.form.type.planEndTime')" prop="projectTaskEndTimeField">
            <el-select
              class="w-100"
              v-model="form.projectTaskEndTimeField"
              :placeholder="$t('projectManage.setting.taskSetting.timeFieldPlace')"
              clearable
              filterable
              @change="updateProjectTaskEndTime"
            >
              <el-option
                v-for="item in paasTimeFields"
                :key="`${item.fieldName}_end`"
                :label="item.displayName"
                :value="item.fieldName"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item :label="$t('projectManage.setting.taskSetting.projectContent')" prop="projectTaskDesc">
            <el-input  type="textarea" maxlength="500" v-model="form.projectTaskDesc" :placeholder="$t('projectManage.setting.taskSetting.placeholder6')" show-word-limit></el-input>
          </el-form-item>
          <el-form-item :label="$t('projectManage.setting.taskSetting.presetTaskWeight')" prop="taskWeight">
            <el-input  type="text" v-model="form.taskWeight" :placeholder="$t('common.base.tip.defaultPlaceholder')"></el-input>
          </el-form-item>
        </el-form>
    </div>
    <div slot="footer">
        <el-button @click="closeDialog">{{$t('common.base.cancel')}}</el-button>
        <el-button :loading="pedding" type="primary" @click="submitForm">{{$t('common.base.save')}}</el-button>
    </div>
  </base-modal>
</template>
<script>

import _ from 'lodash';
import { ConnectorModuleRuleForm } from '@src/modules/connector/components'
import { connectorFromFieldsAddChildren } from '@src/modules/connector/util';
import { createConnectorRuleFormItem } from '@src/modules/connector/util'
import { isEmpty } from 'pub-bbx-utils'
/* api */
import * as ProjectManage from '@src/api/ProjectManage.ts';
import { getFormFieldListInfo } from '@src/api/PassApi.js'
export default {
  name: 'create-task',
  data() {
    return {
      title:  '',
      form: {
        projectTaskName: '',
        projectTaskDesc: '',
        taskType: '',
        taskFormId: '',
        preTaskId: [],
        taskWeight: '',
        projectTaskStartTimeField: '',
        projectTaskEndTimeField: '',
      },
      rules: {
        projectTaskName: [
          { required: true, message: this.$t('projectManage.setting.taskSetting.placeholder2'), trigger: 'blur' },
          { max: 20, message: this.$t('projectManage.setting.taskSetting.ruleMess1'), trigger: 'blur' }
        ],
        taskFormId: [
          {required: true, message: this.$t('projectManage.setting.taskSetting.placeholder3'), trigger: 'change' }
        ],
        taskWeight: [
          {validator: this.validateNonNegative, trigger: 'blur' }
        ],
      },
      taskProps: {
        multiple: false,
        value: 'id',
        label: 'name',
        emitPath: false,
        children: 'formList',
      },
      pedding: false,
      isShow: false,
      isFormEdit: false,
      insertFieldOptionsList:[],
      fromFieldList:[],
      toFieldList:[],
      selectTypeName: '', // 选中的任务类型名称
      preTaskList: [],// 前置任务
      paasTimeFields: [],// paas表单时间字段
      isEmpty,
    }
  },
  props: {
    templateId: {
      type: String | Number,
      default: '',
    },
    typeOptions: {
      type: Array,
      default:(() => [])
    },
    fromType: {
      type: String,
      default: 'setting',
    },
  },
  components: {
    ConnectorModuleRuleForm
  },
  methods: {
    updateProjectTaskEndTime(value) {
      this.form = {...this.form, projectTaskEndTimeField: value};
    },
    updateProjectTaskStartTime(value) {
      this.form = {...this.form, projectTaskStartTimeField: value};
    },
    /**预设任务不能为非负数 */
    validateNonNegative(rule, value, callback) {
      const regex = /^\d+(\.\d+)?$/;
      if (value && !regex.test(value)) {
        callback(new Error(this.$t('member.components.title67')));
      } else {
        callback();
      }
    },
    addRuleFormItem() {
      this.insertFieldOptionsList = [...this.insertFieldOptionsList, createConnectorRuleFormItem()];
    },
    onConnectorSelectRuleFormInputHandler(val) {
      // 添加子属性
      connectorFromFieldsAddChildren(this.fromFieldList);
      this.insertFieldOptionsList = val;
    },
    async openDialog(defaultForm, isEdit) {
      // 设置页面 获取不分页的前置任务列表
      await this.queryPreTaskList(defaultForm) 
      this.title = isEdit ? this.$t('projectManage.setting.taskSetting.editTask') : this.$t('projectManage.setting.taskSetting.createTask')
      this.isFormEdit = isEdit || false

      if (defaultForm) {
        this.$set(this, 'form', _.cloneDeep(defaultForm))
      } else {
        this.$set(this, 'form', {})
      }
      this.$refs['taskForm'].resetFields();
      // 默认获取paas表单字段
      await this.queryTimeFields();
      this.isShow = true
    },

    queryPreTaskList(defaultForm) {
      this.preTaskList = []
      ProjectManage.queryPreTaskList({projectTypeId: this.templateId, id: defaultForm?.id}).then((res) => {
        if (!res.success) return this.$message.error(res.message)
        this.preTaskList = res.data || []
      })
    },

    // paas查询表单的时间字段
    async queryTimeFields() {
      if(this.form.taskType !== 'PAAS_TASK' || isEmpty(this.form.taskFormId)) {
        this.form.projectTaskStartTimeField = ''
        this.form.projectTaskEndTimeField = ''
        return;
      }

      try {
        this.paasTimeFields = [];
        const { success, data} = await getFormFieldListInfo({templateBizId: this.form.taskFormId});
        if(!success) return;

        this.paasTimeFields = data?.paasFormFieldVOList?.filter(item => ['date'].includes(item.formType));

      } catch (e) {
        console.error(e)
      }
    },
    closeDialog() {
      this.isShow = false
    },

    // 改变任务类型
    handleSelectType() {
      this.fields = []
      let dataPath = this.$refs['cascaderType'].getCheckedNodes()?.[0]

      if (dataPath) {
        const { parent, data} = dataPath
        this.form.taskType = parent?.data?.type || '' // 任务类型
        this.form.taskFormName = data?.name || '' // 任务表单名称
        // 更换任务类型清空计划时间字段
        this.form.projectTaskStartTimeField = ''
        this.form.projectTaskEndTimeField = ''
        this.queryTimeFields();
      } 
    },

    submitForm() {
      // 新建任务
      this.pedding = true
      this.$refs['taskForm'].validate((valid) => {
        if (valid) {
          this.pedding = false
          // 校验paas任务的计划开始时间和计划完成时间字段是否一样
          if(this.form.taskType === 'PAAS_TASK'
              && this.form.projectTaskStartTimeField && this.form.projectTaskEndTimeField
              && this.form.projectTaskStartTimeField === this.form.projectTaskEndTimeField) {
            return this.$message.error(this.$t('common.projectManage.settingPassTimeTips'))
          }
          this.$emit('submitTask', _.cloneDeep(this.form), this.isFormEdit)
        } else {
          this.pedding = false
          console.log('error submit!!');
          return false;
        }
      });

     
    }
  }
}
</script>
<style lang="scss">

.task-form {
  .edit-task-form {
    width: 100%;
    padding: 0;
  }
  .w-100 {
    width: 100%;
  }
  .task-cascader {
    width: 100%;
  }
  .steps-wrap {
    margin-bottom: 20px;
  }
  .default-no {
    color: #8a8a8a;
    line-height: 32px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .task-rule-wrap {
    margin: 20px 0;
  }
}
</style>